package com.mingtu.jgspatrol.base;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;

import androidx.viewbinding.ViewBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseActivity;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.base.BaseBindingActivity;
import com.mingtu.common.callback.StringDialogCallback;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.room.ReportedEvent;
import com.mingtu.common.room.ReportedEventDao;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.room.SignInEvent;
import com.mingtu.jgspatrol.room.SignInEventDao;
import com.mingtu.jgspatrol.utils.MyConstant;
import com.mingtu.uploadevent.bean.UploadFileResultBean;
import com.mingtu.uploadevent.callback.UploadCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2021-6-3 10:16:29
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class MyBaseActivity<VB extends ViewBinding> extends BaseBindingActivity<VB> {
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 200:
                    ReportedEvent reportedEvent = (ReportedEvent) msg.obj;
                    int id = reportedEvent.getId();
                    String address = reportedEvent.getAddress();
                    String lat = reportedEvent.getLat();
                    String lng = reportedEvent.getLng();
                    String memo = reportedEvent.getMemo();
                    String tag = reportedEvent.getTag();
                    String uploadType = reportedEvent.getUploadType();
                    String createTime = reportedEvent.getCreateTime();
                    String myCreateTime = MyUtills.stampToDateTime2(createTime);
                    ArrayList<LinkedHashMap<String, Object>> picVideoArray = reportedEvent.getPicVideoArray();

                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("address", address);
                    hashMap.put("lat", lat);
                    hashMap.put("lng", lng);
                    hashMap.put("eventDesc", memo);
                    if (!StringUtils.isEmpty(tag)) {
                        hashMap.put("tag", tag);
                    }
                    hashMap.put("attachVOS", picVideoArray);
                    hashMap.put("type", uploadType);
                    hashMap.put("createTime", myCreateTime);
                    String str = GsonUtils.toJson(hashMap);


                    OkGo.<String>post(Constant.getInstance().POST_UPLOAD_EVENT)
                            .tag(this)
                            .upJson(str)
                            .execute(new StringDialogCallback(ActivityUtil.getTopActivity()) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    String result = response.body();
                                    if (!StringUtils.isEmpty(result)) {
                                        JSONObject jsonObject = JSON.parseObject(result);
                                        String msg = jsonObject.getString("msg");
                                        if (msg.equals(Constant.RESULT_SUCCESS)) {
                                            reportedEventDao.deleteEvent(id);
                                            EventBus.getDefault().post(new MyEventBus(Constant.getInstance().REFRESH_MY_REPORT_DATA));
                                        } else {
                                            MyLogUtil.e("BaseActivity", "离线的数据上传失败");
                                        }

                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    String result = response.body();
                                    MyLogUtil.e(getClass().getSimpleName(), "离线的数据上传失败");
                                }
                            });


                    break;


                case 300:
                    SignInEvent signInEvent = (SignInEvent) msg.obj;
                    int signInEventId = signInEvent.getId();
                    String mylat = signInEvent.getLat();
                    String mylng = signInEvent.getLng();
                    String content = signInEvent.getContent();
                    String clockTime = signInEvent.getClockTime();
                    ArrayList<LinkedHashMap<String, Object>> myPicVideoArray = signInEvent.getPicVideoArray();

                    HashMap<String, Object> myHashMap = new HashMap<>();
                    myHashMap.put("lnglat", mylng + "," + mylat);
                    myHashMap.put("content", content);
                    myHashMap.put("taskClockAttachVOList", myPicVideoArray);
                    myHashMap.put("clockTime", clockTime);
                    String mystr = GsonUtils.toJson(myHashMap);

                    OkGo.<String>post(MyConstant.getInstance().POST_CLOCK_TASK)
                            .tag(this)
                            .upJson(mystr)
                            .execute(new StringDialogCallback(ActivityUtil.getTopActivity()) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    String result = response.body();
                                    if (!StringUtils.isEmpty(result)) {
                                        JSONObject jsonObject = JSON.parseObject(result);
                                        String msg = jsonObject.getString("msg");
                                        if (msg.equals(Constant.RESULT_SUCCESS)) {
                                            signInEventDao.deleteEvent(signInEventId);
                                            EventBus.getDefault().post(new MyEventBus(MyConstant.getInstance().REFRESH_MY_SIGN_IN_DATA));
                                        } else {
                                            MyLogUtil.e("BaseActivity", "离线的数据上传失败");
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    String result = response.body();
                                    MyLogUtil.e(getClass().getSimpleName(), "离线的数据上传失败");
                                }
                            });


                    break;
                default:
                    break;
            }
        }
    };
    private ReportedEventDao reportedEventDao;
    private List<ReportedEvent> reportedEventList;
    private SignInEventDao signInEventDao;
    private List<SignInEvent> signInEventList;

    @Override
    protected int getLayoutId() {
        return 0;
    }

    @Override
    protected void initView() {
        setStatusBarBackground(getResources().getDrawable(R.drawable.shape_bg_title));
        setTitleBarBackground(getResources().getDrawable(R.drawable.shape_bg_title));
        setTopLeftButton(R.mipmap.icon_back_white);
        setModuleTitleColor(R.color.white);

        ImmersionBar immersionBar = ImmersionBar.with(this);
        immersionBar.statusBarDarkFont(false);
        immersionBar.init();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void getData() {

    }

    @Override
    protected void onPause() {
        MyLogUtil.e(getClass().getSimpleName(), "onPause======");
        super.onPause();
    }

    @Override
    protected void onResume() {
        MyLogUtil.e(getClass().getSimpleName(), "onResume======");

        super.onResume();
    }

    @Override
    protected void onStop() {
        MyLogUtil.e(getClass().getSimpleName(), "onStop======");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        MyLogUtil.e(getClass().getSimpleName(), "onStop======");
        super.onDestroy();
    }

//    @Override
//    public void onConnected(NetworkUtils.NetworkType networkType) {
//        super.onConnected(networkType);
//        //启动app之后，网络变化执行
//        if (!flag) {
//            Activity topActivity = ActivityUtil.getTopActivity(); //防止重复请求上传
//            if (getClass().getName().equals(topActivity.getPackageName() + "." + topActivity.getLocalClassName())) {
//                uploadReport();
//            }
//        }
//
//    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        //启动的app的时候执行
        if (netWorkState) {
            Activity topActivity = ActivityUtil.getTopActivity(); //防止重复请求上传
            if (topActivity != null && getClass().getName().equals(topActivity.getPackageName() + "." + topActivity.getLocalClassName())) {
//                MyLogUtil.e("testtest","topActivity==" + getClass().getName() + "======" + topActivity.getPackageName() + "." + topActivity.getLocalClassName());
                String token = SPStaticUtils.getString(SPTools.token);
                //离线上报
                reportedEventDao = BaseApplication.getBaseApplication().getReportedEventDao();
                reportedEventList = reportedEventDao.getAll();
                if (reportedEventList.size() > 0) {
                    if (!StringUtils.isEmpty(token)) {
                        uploadReport();
                    }
                }

                //离线签到
                signInEventDao = Application.getApplication().getSignInEventDao();
                signInEventList = signInEventDao.getAll();
                if (signInEventList.size() > 0) {
                    if (!StringUtils.isEmpty(token)) {
                        uploadSignInData();
                    }
                }
            }
        }
    }

    /**
     * 连接网络之后上传上报信息
     *
     * @param
     * @return
     */

    private void uploadReport() {
        if (reportedEventDao != null) {
            reportedEventList = reportedEventDao.getAll();
            if (netWorkState && reportedEventList.size() > 0) {
                for (int i = 0; i < reportedEventList.size(); i++) {
                    ArrayList<LinkedHashMap<String, Object>> picVideoArray = new ArrayList<>();
                    ReportedEvent reportedEvent = reportedEventList.get(i);
                    List<ReportedEvent.MyattachVOSBean> myattachVOSBeans = reportedEvent.getMyattachVOS();
                    int size = myattachVOSBeans.size();
                    for (int j = 0; j < size; j++) {
                        ReportedEvent.MyattachVOSBean myattachVOSBean = myattachVOSBeans.get(j);
                        String pathName = myattachVOSBean.getPathName();
                        String type = myattachVOSBean.getType();       //type : 1: 第一张照片 ,2 第二张照片 ，3 视频,

                        ArrayList<File> files = new ArrayList<>();
                        File file = new File(pathName);
                        files.add(file);
                        uploadFile(files, new UploadCallback() {
                            @Override
                            public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                                if (urlBeans != null) {
                                    int size = urlBeans.size();
                                    if (size > 0) {
                                        for (int i = 0; i < size; i++) {
                                            String url = urlBeans.get(i).getUrl();
                                            LinkedHashMap picVidoInfo = new LinkedHashMap<>();
                                            picVidoInfo.put("type", type);
                                            picVidoInfo.put("url", url);
                                            picVideoArray.add(picVidoInfo);

//                                            if (PictureMimeType.isUrlHasVideo(url)) {
//                                                FileUtils.delete(file); //因为之前保存的是压缩之后的路径，这里离线上传完成功之后删除压缩视频文件
//                                            }

                                            if (myattachVOSBeans.size() == picVideoArray.size()) {
                                                reportedEvent.setPicVideoArray(picVideoArray); //将上传的数据传到handler中
                                                Message message = Message.obtain();
                                                message.obj = reportedEvent;
                                                message.what = 200;
                                                handler.sendMessage(message);
                                            }
                                        }
                                    }
                                }
                            }
                        });

                    }
                }
            }


        }


    }

    private void uploadSignInData() {
        if (signInEventDao != null) {
            if (netWorkState && signInEventList.size() > 0) {
                for (int i = 0; i < signInEventList.size(); i++) {
                    ArrayList<LinkedHashMap<String, Object>> picVideoArray = new ArrayList<>();
                    SignInEvent signInEvent = signInEventList.get(i);
                    List<SignInEvent.MyattachVOSBean> myattachVOSBeans = signInEvent.getMyattachVOS();
                    int size = myattachVOSBeans.size();
                    for (int j = 0; j < size; j++) {
                        SignInEvent.MyattachVOSBean myattachVOSBean = myattachVOSBeans.get(j);
                        String pathName = myattachVOSBean.getPathName();
                        ArrayList<File> files = new ArrayList<>();
                        File file = new File(pathName);
                        files.add(file);
                        uploadFile(files, new UploadCallback() {
                            @Override
                            public void result(List<UploadFileResultBean.DataBean.UrlBean> urlBeans) {
                                if (urlBeans != null) {
                                    int size = urlBeans.size();
                                    if (size > 0) {
                                        for (int i = 0; i < size; i++) {
                                            String url = urlBeans.get(i).getUrl();
                                            LinkedHashMap picVidoInfo = new LinkedHashMap<>();
                                            picVidoInfo.put("url", url);
                                            picVideoArray.add(picVidoInfo);

//                                            if (PictureMimeType.isUrlHasVideo(url)) {
//                                                FileUtils.delete(file); //因为之前保存的是压缩之后的路径，这里离线上传完成功之后删除压缩视频文件
//                                            }

                                            if (myattachVOSBeans.size() == picVideoArray.size()) {
                                                signInEvent.setPicVideoArray(picVideoArray); //将上传的数据传到handler中
                                                Message message = Message.obtain();
                                                message.obj = signInEvent;
                                                message.what = 300;
                                                handler.sendMessage(message);
                                            }
                                        }
                                    }
                                }
                            }
                        });

                    }
                }
            }


        }


    }

    /**
     * 上传图片、视频(目前接口只支持单张上传，要支持多张上传的话需要更改逻辑)
     */
    private void uploadFile(ArrayList<File> files, final UploadCallback uploadCallback) {
        OkGo.<String>post(Constant.getInstance().POST_UPLOAD_FILE)
                .tag(this)
                .addFileParams("files", files)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            UploadFileResultBean resultBean = new UploadFileResultBean();
                            resultBean = gson.fromJson(result, UploadFileResultBean.class);
                            List<UploadFileResultBean.DataBean.UrlBean> urlBeans = resultBean.getData().getUrl();
                            uploadCallback.result(urlBeans);
                        } else {
                            uploadCallback.result(null);
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        uploadCallback.result(null);
                    }
                });
    }

}
